# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myMiddleware
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/3 11:34
@desc: 系统的中间件
========================================================================================================================
"""
from sanic import Sanic
from config import config
from utils.myResFormat import ResultCode, ResultJson
from sanic.response import json as JsonResponse
from middleware.myAuthorization import Authorization
from middleware.myProcessLog import ProcessLog
from typing import Union
from utils.myLog import SimpleLog
import traceback

app = Sanic.get_app(config.PROJECT_NAME)


@app.middleware('request')
async def process_request(request) -> Union[None, JsonResponse]:
    """视图前--记录请求日志，鉴权功能"""

    # 记录请求日志
    ProcessLog(request=request, response=None).action()

    # 在header里面增加用户信息
    await Authorization.get_user_info(request)

    # 检查白名单
    if not Authorization.white_list_check(request):
        user_info = request.headers.user_info
        if not user_info:
            return JsonResponse(ResultJson(ResultCode.TOKEN_ERROR).result)


@app.middleware('response')
async def process_response(request, response) -> None:
    """视图后--记录返回日志（做映射）"""
    ProcessLog(request=request, response=response).action()


@app.exception(Exception)
async def process_error(request, exception) -> JsonResponse:
    """异常情况处理"""
    SimpleLog.error("traceback_error: " + traceback.format_exc())
    return JsonResponse(ResultJson(ResultCode.SERVER_ERROR, description=str(exception)).result)
